package com.zw.cc.controller;

import com.zw.cc.base.BaseResult;
import com.zw.cc.base.ExceVariables;
import com.zw.cc.model.UserLoginEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by zwz
 * date 2016/12/15
 * project com.zw.cc.controller
 */
@Controller
public class LoginCtrl {

    /**如果使用 Validated
     * 1， 通用拦截器 拦截 BindException  但是处理返回结果不太灵活
     * 2， 使用BindingResult result 作为参数传入的话，可以用hasErrors判断 自定义处理结果
     *
     * @param userLoginEntity
     * @param result
     * @param model
     * @return
     */
    @RequestMapping(value = "/login")
    public String Login(@Validated UserLoginEntity userLoginEntity, BindingResult result, Model model) {
        if(result.hasErrors()){
            String field = result.getFieldError().getField();
            String msg = result.getFieldError().getDefaultMessage();
            model.addAttribute("result", new BaseResult(ExceVariables.FAILURE, field + msg));
            return "/login";
        }
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token;
        try {
            token = new UsernamePasswordToken(userLoginEntity.getAccount(), userLoginEntity.getPassword());
            token.setRememberMe(true);
            currentUser.login(token);
        } catch ( AuthenticationException ae ) {
            model.addAttribute("result", new BaseResult(ExceVariables.ACCOUNT_PWD_ERROR));
            return "/login";
        }
        return "/";
    }
    @RequestMapping("/admin")
    public String userLogin() {
        return "home";
    }
    @RequestMapping("/admin/home")
    public String userLogin1() {
        return "home";
    }
    @RequestMapping(value = "/pageLogin",method = RequestMethod.GET)
    public String pageLogin() {
        return "login";
    }
}
